package com.xbongbong.saas.analytical.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.help.team.TeamUserHelp;
import com.xbongbong.paas.pojo.dto.ValidateDataDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.analytical.SaasValidateAnalyticalService;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.domain.entity.PublicGroupSeniorEntity;
import com.xbongbong.saas.domain.entity.ext.ClueEntityExt;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.dictionary.ClueStatusEnum;
import com.xbongbong.saas.help.SaasDataInitHelp;
import com.xbongbong.saas.help.SaveFormatHelp;
import com.xbongbong.saas.model.ClueModel;
import com.xbongbong.saas.model.PublicGroupSeniorModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2021/07/15 17:15
 */
@Service("clueAnalyticalServiceImpl")
public class ClueValidateAnalyticalServiceImpl implements SaasValidateAnalyticalService {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(ClueValidateAnalyticalServiceImpl.class);
    
    @Resource
    private ClueModel clueModel;
    @Resource
    private TeamUserHelp teamUserHelp;
    @Resource
    private PublicGroupSeniorModel publicGroupSeniorModel;

    @Override
    public List<Integer> type() {
        return Arrays.asList(XbbRefTypeEnum.CLUE.getCode());
    }

    @Override
    public void analyticalData(ValidateDataDTO validateDataDTO) throws XbbException {
        beforeSave(validateDataDTO);
        if (CollectionsUtil.isNotEmpty(validateDataDTO.getOwnerIds()) || CollectionsUtil.isNotEmpty(validateDataDTO.getCoUserId()) || Objects.equals(validateDataDTO.getIsImport(), BasicConstant.ONE) || (!Objects.equals(validateDataDTO.getSubBusinessType(), XbbRefTypeEnum.CLUE_PUBLIC.getCode()) && !Objects.equals(validateDataDTO.getFromOuterLink(), 1))) {
            teamUserHelp.beforeVerifyUserTeam(validateDataDTO);
        }
    }
    
    public void beforeSave(ValidateDataDTO validateDataDTO) throws XbbException {
        try {
            JSONObject data = validateDataDTO.getData();
            String corpid = validateDataDTO.getCorpid();
            Long formId = validateDataDTO.getFormId();
            Long dataId = validateDataDTO.getDataId();
            //将关联的市场活动id和名称分开存到两个字段里
            SaveFormatHelp.formatLinkBusiness4Save(data, ClueEnum.MARKET_ACTIVITY_ID.getAttr(), ClueEnum.MARKET_ACTIVITY_NAME.getAttr(), ClueEnum.MARKET_ACTIVITY_NAME.getFieldType());

            data.put(ClueEnum.IS_PUBLIC.getAttr(), 0);
            if (Objects.isNull(validateDataDTO.getOwnerIds()) || (Objects.nonNull(validateDataDTO.getOwnerIds()) && validateDataDTO.getOwnerIds().isEmpty())) {
                // 新建无负责人，默认为公海线索
                data.put(ClueEnum.IS_PUBLIC.getAttr(),1);
            } else {
                // 新建有负责人设置其分配时间
                if (dataId == null) {
                    data.put(ClueEnum.DISTRIBUTION_DATE.getAttr(), DateTimeUtil.getInt());
                }
            }
            if (Objects.isNull(dataId)) {
                // 线索新建的默认状态为待处理
                data.put(ClueEnum.CLUE_STATUS.getAttr(), ClueStatusEnum.PENDING.getCode());
            }
            if (dataId != null && Objects.equals(validateDataDTO.getIsImport(), 1)) {
                // 线索阶段不允许编辑
                ClueEntityExt clueEntityExt = clueModel.getByKey(dataId, corpid);
                if (Objects.isNull(clueEntityExt)) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
                }
                String oldStageCode = FastJsonHelper.getStringOrDefaultFromFormData(clueEntityExt.getData(), ClueEnum.CLUE_STAGE.getAttr(),  "");
                String oldInvalid = FastJsonHelper.getStringOrDefaultFromFormData(clueEntityExt.getData(), ClueEnum.INVALID_REASON.getAttr(), "");
                data.put(ClueEnum.CLUE_STAGE.getAttr(), oldStageCode);
                data.put(ClueEnum.INVALID_REASON.getAttr(), oldInvalid);

                // 导入，线索状态不允许修改
                String oldStatus = FastJsonHelper.getStringOrDefaultFromFormData(clueEntityExt.getData(), ClueEnum.CLUE_STATUS.getAttr(), ClueStatusEnum.PENDING.getCode());
                data.put(ClueEnum.CLUE_STATUS.getAttr(), oldStatus);
            }

            if (Objects.nonNull(dataId) && dataId !=0) {
                //所属分组不允许编辑.不允许覆盖导入
                ClueEntityExt clueEntityExt = clueModel.getByKey(dataId, corpid);
                String oldPublicGroup = FastJsonHelper.getStringOrDefaultFromFormData(clueEntityExt.getData(), ClueEnum.PUBLIC_GROUP.getAttr(),  "");
                data.put(ClueEnum.PUBLIC_GROUP.getAttr(), oldPublicGroup);
                Object oldBackNum = clueEntityExt.getData().get(ClueEnum.BACK_NUM.getAttr());
                if (Objects.isNull(oldBackNum)) {
                    data.remove(ClueEnum.BACK_NUM.getAttr());
                } else {
                    data.put(ClueEnum.BACK_NUM.getAttr(), oldBackNum);
                }
            }

            if (Objects.isNull(dataId)) {
                //新建
                if (Objects.equals(validateDataDTO.getIsImport(), 1)) {
                    //新建导入
                    //所属分组
                    LOGGER.info("步骤1导入绑定所属分组");
                    String newPublicGroup = FastJsonHelper.getStringOrDefaultFromFormData(data, ClueEnum.PUBLIC_GROUP.getAttr(),  "");
                    if (StringUtil.isNotEmpty(newPublicGroup)) {
                        List<PublicGroupSeniorEntity> groupNameList = publicGroupSeniorModel.getByGroupName(newPublicGroup, formId, corpid,BasicConstant.ONE);
                        if (CollectionsUtil.isNotEmpty(groupNameList)) {
                            PublicGroupSeniorEntity publicGroupSeniorEntity = groupNameList.get(0);
                            if (!Objects.equals(publicGroupSeniorEntity.getGroupType(), BasicConstant.TWO)) {
                                LOGGER.info("步骤2导入绑定所属分组成功");
                                data.put(ClueEnum.PUBLIC_GROUP.getAttr(), publicGroupSeniorEntity.getId());
                            } else {
                                //无分组 直接不用绑定
                                data.remove(ClueEnum.PUBLIC_GROUP.getAttr());
                            }
                        } else {
                            data.remove(ClueEnum.PUBLIC_GROUP.getAttr());
                        }
                    }
                } else {
                    //其他新建这里直接移除掉该字段
                    data.remove(ClueEnum.PUBLIC_GROUP.getAttr());
                }
                //退回次数不支持任何场景的新建
                data.remove(ClueEnum.BACK_NUM.getAttr());
            }

            // 赋予默认值
            for (Map.Entry<String,Object> entry : SaasDataInitHelp.initClue().entrySet()){
                SaasDataInitHelp.antDataSet(data,entry.getKey(),entry.getValue());
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOGGER.error("clueAnalyticalServiceImpl.beforeSave error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }
}
